# -*- coding: UTF-8 -*-
from . import BaseController
from backend.models import PriceType, PriceTypeDetail, PriceTypePriceTypeDetail, VideoOrder
from backend.libs import myjson as json
from django.db import connection
from datetime import datetime


class PriceTypeOptionsController(BaseController):

    def get(self):
        """获取类目选项列表
        """
        price_type_in_db = PriceType.objects.order_by('show_order').all()
        options = [ p.to_options_dict() for p in price_type_in_db ]
        data = {
            'options': options
        }
        return self.render_json(data=data)


class AllPriceTypeController(BaseController):

    def get(self):
        """获取所有类目
        """
        price_type_in_db = PriceType.objects.order_by('show_order').all()
        price_type = [ p.to_dynamic_form_dict(m2m_fields=['pricetypedetail_set']) for p in price_type_in_db ]
        data = {
            "inline": True,
            "labelPosition": "right",
            "labelWidth": "",
            "size": "small",
            "statusIcon": True,
            "formItemList": price_type
        }
        return self.render_json(data=data)


class PriceTypeDetailListController(BaseController):

    def get(self):
        pt_detail = PriceTypeDetail.objects

        type_detail_name = self.get_argument('typeDetailName', '')
        if type_detail_name:
            pt_detail = pt_detail.filter(name__contains=type_detail_name)
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(pt_detail.all(), number_per_page=number_per_page, m2m_fields=['price_type'])
        return self.render_json(data=paginator)    


class DelPriceTypeDetailController(BaseController):

    def post(self, price_type_detail_id):
        price_type_detail_id = int(price_type_detail_id)
        if price_type_detail_id <= 0:
            return self.render_json(code=1000, msg='参数无效')
        video_order = VideoOrder.objects.filter(price_type_detail__id=price_type_detail_id).all()
        if len(video_order) > 0:
            return self.render_json(code=1001, msg='该价格因子关联了视频订单！无法删除！')
        price_type_detail = PriceTypeDetail.objects.filter(id=price_type_detail_id).first()
        if price_type_detail:
            PriceTypePriceTypeDetail.deletePriceTypeDetailRel(price_type_detail);
            cursor=connection.cursor()
            sql = 'delete from app_pricetypedetail where id=%s' % price_type_detail_id
            cursor.execute(sql)
        return self.render_json()    


class CreatePriceTypeController(BaseController):

    def post(self):
        """创建价格类目
        """
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='类目名称不能为空')
        price_type_id = data['id']

        price_type = PriceType() if int(price_type_id) <= 0 else PriceType.objects.filter(id=price_type_id).first()
        price_type.name = data['name']
        price_type.desc = data['desc']
        price_type.icon = data['icon']
        price_type.type = data['type']
        price_type.state = data['state']
        price_type.show_order = data['showOrder']
        price_type.save()
        return self.render_json(data=price_type.to_dict())


class CreatePriceTypeDetailController(BaseController):

    def post(self):
        """创建价格因子
        """
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='因子名称不能为空')
        price_type_detail_id = data['id']

        if int(price_type_detail_id) <= 0:
            price_type_detail = PriceTypeDetail()
        else:
            price_type_detail = PriceTypeDetail.objects.filter(id=price_type_detail_id).first()
            if not price_type_detail:
                return self.render_json(code=1001, msg='指定id的因子数据未找到')
            # 更新的话每次都重新创建关联关系
            PriceTypePriceTypeDetail.deletePriceTypeDetailRel(price_type_detail);

        price_type_detail.name = data['name']
        price_type_detail.desc = data['desc']
        price_type_detail.price = int(data['price']) if int(data['price']) >= 0 else 0
        transaction_price = int(data['transaction_price'])
        price_type_detail.transaction_price = transaction_price if transaction_price >= 0 else 0
        price_type_detail.state = data['state']
        price_type_detail.show_order = data['showOrder']
        price_type_detail.create_time = datetime.now()
        price_type_detail.save()

        price_type_id = data['priceTypeId']
        if price_type_id:
            price_type_id = int(price_type_id)
            price_type = PriceType.objects.filter(id=price_type_id).first()
            if price_type:
                ptptd = PriceTypePriceTypeDetail.objects.create(pricetype=price_type, pricetypedetail=price_type_detail)
                ptptd.save()

        return self.render_json(data=price_type_detail.to_dict())